#pragma once
#include <iostream>
#include <sys/epoll.h>
#include <sys/types.h>
#include "Socket.hpp"

using namespace SocketModule;
using namespace LogMudule;

const int gdefaultfd = -1;
#define MAX 4096
class EpollSever
{
public:
    EpollSever(uint16_t port)
        : _socket(std::make_unique<TcpSocket>()),
          _isrunning(false),
          _port(port),
          _epfd(gdefaultfd)
    {
    }
    ~EpollSever()
    {
        _socket->Close();
        if (_epfd >= 0)
            close(_epfd);
    }
    void Init()
    {
        _socket->BuildTcpSocket(_port);
        // 1. 创建epoll模型
        _epfd = epoll_create(256);
        if (_epfd < 0)
        {
            LOG(LogLevel::ERROR) << "epoll error";
            exit(EPOLL_CREAT_ERR);
        }
        LOG(LogLevel::INFO) << "epoll sucess " << _socket->Fd();
        // 2.将listen套接字接入epoll
        struct epoll_event ev;
        ev.events = EPOLLIN;
        ev.data.fd = _socket->Fd();
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _socket->Fd(), &ev);
        if (n < 0)
        {
            LOG(LogLevel::ERROR) << "epoll_ctl error";
            exit(EPOLL_CTL_ERR);
        }
    }
    void Start()
    {
        int timeout = -1;
        _isrunning = true;
        while (true)
        {
            int n = epoll_wait(_epfd, _resfd, MAX, timeout);
            switch (n)
            {
            case 0:
                std::cout << "time out" << std::endl;
                break;
            case -1:
                perror("epoll_wait");
                break;
            default:
                std::cout << "已有用户准备就绪" << std::endl;
                Dispatcher();
                break;
            }
        }
        _isrunning = false;
    }
    void Dispatcher()
    {
        for (int i = 0; i < MAX; i++)
        {
            if (_resfd[i].data.fd == gdefaultfd)
                continue;
            // 判断是否在rfds集合中
            if (_resfd[i].data.fd == _socket->Fd())
            {
                if (_resfd[i].events & EPOLLIN)
                    Accpetor();
            }
            else
            {
                if (_resfd[i].events & EPOLLIN)
                    Recver(_resfd[i].data.fd);
            }
        }
    }
    void Recver(int fd)
    {
        char buffer[1024];
        int n = recv(fd, buffer, sizeof(buffer) - 1, 0);
        LOG(LogLevel::DEBUG) << "+++++++++++++++++++++++++++++";
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << "cilent: #" << buffer << std::endl;
            std::string message;
            message += "Echo #";
            message += buffer;
            send(fd, message.c_str(), message.size(), 0);
        }
        else if (n == 0)
        {
            LOG(LogLevel::INFO) << "客户端退出 ：" << fd;
            int n = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                return;
            }
            LOG(LogLevel::DEBUG) << "epoll_ctl success: " << fd;
            close(fd);
        }
        else
        {
            LOG(LogLevel::DEBUG) << "客户端读取出错, sockfd: " << fd;
            // 把fd从epoll中移除
            int m = epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            if (m < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                return;
            }
            LOG(LogLevel::DEBUG) << "epoll_ctl success: " << fd;
            close(fd);
        }
    }
    void Accpetor()
    {
        InetAddr client;
        int newfd = _socket->Accept(&client);
        if (newfd < 0)
            return;
        // 加入托管
        else
        {
            std::cout << "获得了一个新的链接: " << newfd << " client info: " << client.Addr() << std::endl;
            struct epoll_event ev;
            ev.data.fd = newfd;
            ev.events = EPOLLIN;
            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, newfd, &ev);
            if (n < 0)
            {
                LOG(LogLevel::ERROR) << "epoll_ctl error";
                close(newfd);
            }
            LOG(LogLevel::DEBUG) << "epoll_ctl success: " << newfd;
        }
    }

private:
    std::unique_ptr<Socket> _socket;
    bool _isrunning;
    int _epfd;
    u_int16_t _port;
    struct epoll_event _resfd[MAX];
};
